<?php
require_once 'core.php';
require_once 'errors.php';
require_once 'authentication.php';
$postdata = json_decode($_POST[postdata]);

//mysql_query("INSERT INTO `req` (`text`) VALUES ($postdata);");

$log = time()."---".$_POST[postdata]."\n";

file_put_contents("logs/importLog.txt", $log, FILE_APPEND);

$login              =       $postdata->login;
$password           =       $postdata->password;
$batch_name         =       $postdata->batch_name;
$originator         =       $postdata->originator ;         //*
$phones_list        =       $postdata->phones_list;
$send_date          =       $postdata->send_date;           //*
$end_date           =       $postdata->end_date;            //*
$week_from_time     =       $postdata->week_from_time;      //*
$week_to_time       =       $postdata->week_to_time;        //*
$weekend_from_time  =       $postdata->weekend_from_time;   //*
$weekend_to_time    =       $postdata->weekend_to_time;     //*
$retry_time         =       $postdata->retry_time;          //*
$max_sum_listen_time=       $postdata->max_sum_listen_time ;//*
$done_listen_time   =       $postdata->done_listen_time;    //*
$gap                =       $postdata->gap;                 //*
$answer_wait_time   =       $postdata->answer_wait_time;    //*
$max_retries        =       $postdata->max_retries;         //*

if (empty($login) || empty($password) || empty($batch_name) || empty($phones_list)) {
    $error = 42;
    $request_id = 0;
    
} else {    
    $authentication = new authentication($login, $password);
    if ($authentication->check()) {
        
        mysql_query(
                "INSERT INTO `request` 
                        (`name`     ,`datetime` , `start_datetime`, `end_datetime`,  `week_from_time`,  `week_to_time`, `weekend_from_time` , `weekend_to_time`, `retry_time` , `answer_wait_time`, `max_retries`, `max_sum_listen_time`, `done_listen_time`, `gap`) 
                VALUES  ('$batch_name', NOW()    , '$send_date'   , '$end_date'   ,  '$week_from_time', '$week_to_time','$weekend_from_time', '$week_to_time'  , '$retry_time', '$answer_wait_time','$max_retries','$max_sum_listen_time','$done_listen_time','$gap')");
        
        $request_id = mysql_insert_id();
        $request_details = str_replace("(", "($request_id ,", $phones_list);
        
        mysql_query(
                "INSERT INTO `request_details` (`request_id`, `phone_number`, `money`, `expiration_type`) 
                                     VALUES $request_details");
        $error = 0;
        
        //require_once 'index.php';
        
    } else {
        $error = 4;
        $request_id = 0;
    }
}

$getError = new getError($error, $request_id);
echo $getError->getJson();